package com.ruoyi.quartz.util;


import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class HttpUtils {
    private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);

    private static final int REQUEST_TIMEOUT = 5000;

    private static final int CONNECT_TIMEOUT = 5000;

    private static final int SO_TIMEOUT = 5000;

    private static final String ENCODING = "UTF-8";

    private static CloseableHttpClient client;

    static {
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(5000).build();
        client = HttpClients.custom().setDefaultRequestConfig(requestConfig).setMaxConnTotal(50).build();
    }

    public static String get(String url, Map<String, String> paramsMap) {
        return send(RequestBuilder.get(url), paramsMap);
    }

    public static String post(String url, Map<String, String> paramsMap) {
        return send(RequestBuilder.post(url), paramsMap);
    }

    public static String post(String requestUrl, String accessToken, String params) throws Exception {
        String contentType = "application/x-www-form-urlencoded";
        return post(requestUrl, accessToken, contentType, params);
    }

    public static String post(String requestUrl, String accessToken, String contentType, String params) throws Exception {
        String encoding = "UTF-8";
        if (requestUrl.contains("nlp"))
            encoding = "GBK";
        return post(requestUrl, accessToken, contentType, params, encoding);
    }

    public static String post(String requestUrl, String accessToken, String contentType, String params, String encoding) throws Exception {
        String url = requestUrl + "?access_token=" + accessToken;
        return postGeneralUrl(url, contentType, params, encoding);
    }

    public static String postGeneralUrl(String generalUrl, String contentType, String params, String encoding) throws Exception {
        URL url = new URL(generalUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", contentType);
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setConnectTimeout(3000);
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.write(params.getBytes(encoding));
        out.flush();
        out.close();
        connection.connect();
        Map<String, List<String>> headers = connection.getHeaderFields();
        for (String key : headers.keySet())
            System.err.println(key + "--->" + headers.get(key));
        BufferedReader in = null;
        in = new BufferedReader(new InputStreamReader(connection.getInputStream(), encoding));
        String result = "";
        String getLine;
        while ((getLine = in.readLine()) != null)
            result = result + getLine;
        in.close();
        System.err.println("result:" + result);
        return result;
    }

    public static String send(RequestBuilder requestBuilder, Map<String, String> paramsMap) {
        requestBuilder.setCharset(Charset.forName("UTF-8"));
        String responseText = "";
        if (paramsMap != null) {
            for (Map.Entry<String, String> param : paramsMap.entrySet())
                requestBuilder.addParameter(param.getKey(), param.getValue());
            CloseableHttpResponse response = null;
            try {
                response = client.execute(requestBuilder.build());
                if (response.getStatusLine().getStatusCode() == 200) {
                    HttpEntity entity = response.getEntity();
                    if (entity != null)
                        responseText = EntityUtils.toString(entity, "UTF-8");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    response.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return responseText;
    }

    public static String postHeader(String url, Map<String, String> paramsMap, String appkey) throws Exception {
        RequestBuilder post = RequestBuilder.post(url);
        post.setCharset(Charset.forName("UTF-8"));
        post.setHeader("Content-Type", "application/x-www-form-urlencoded");
        post.setHeader("Appkey", appkey);
        String responseText = "";
        if (paramsMap != null) {
            for (Map.Entry<String, String> param : paramsMap.entrySet())
                post.addParameter(param.getKey(), param.getValue());
            CloseableHttpResponse response = null;
            try {
                response = client.execute(post.build());
                if (response.getStatusLine().getStatusCode() == 200) {
                    HttpEntity entity = response.getEntity();
                    if (entity != null)
                        responseText = EntityUtils.toString(entity, "UTF-8");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    response.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return responseText;
    }

    public static JSONObject postResponse(String path, String access_tokens, JSONObject Info) throws IOException {
        DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
        HttpPost post = new HttpPost(path);

        post.addHeader("Authorization", access_tokens);
        String result = "";
        try {
            StringEntity s = new StringEntity(Info.toString(), "utf-8");
            s.setContentEncoding((Header) new BasicHeader("Content-Type", "application/json"));
            post.setEntity((HttpEntity) s);
            HttpResponse httpResponse = defaultHttpClient.execute((HttpUriRequest) post);
            InputStream inStream = httpResponse.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));
            StringBuilder strber = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null)
                strber.append(line + "\n");
            inStream.close();
            result = strber.toString();
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                System.out.println("");
            } else {
                System.out.println("");
            }
        } catch (Exception e) {
            System.out.println("");
            e.printStackTrace();
        }
        return JSONObject.parseObject(result);
    }

    public static String postBody(String path, String parm) throws IOException {
        CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(path);
        post.setHeader("Content-Type", "application/json");
//        post.setHeader("Content-Length", "64");
//        post.setHeader("Host", "127.0.0.1");
        String result = "";
        try {
            StringEntity s = new StringEntity(parm, "utf-8");
            s.setContentEncoding((Header) new BasicHeader("Content-Type", "application/json"));
            post.setEntity((HttpEntity) s);
            HttpResponse httpResponse = closeableHttpClient.execute((HttpUriRequest) post);
            InputStream inStream = httpResponse.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));
            StringBuilder strber = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null)
                strber.append(line + "\n");
            inStream.close();
            result = strber.toString();
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                System.out.println("");
            } else {
                System.out.println("");
            }
        } catch (Exception e) {
            System.out.println("");
            throw new RuntimeException(e);
        }
        return result;
    }

    public static String postHeaderFace(String url, Map<String, String> paramsMap, String Content_type, String authorization, String Accept) {
        RequestBuilder post = RequestBuilder.post(url);
        post.setCharset(Charset.forName("UTF-8"));
        post.setHeader("Content-Type", Content_type);
        post.setHeader("Authorization", authorization);
        if (Accept != null)
            post.setHeader("Accept", Accept);
        String responseText = "";
        if (paramsMap != null) {
            for (Map.Entry<String, String> param : paramsMap.entrySet())
                post.addParameter(param.getKey(), param.getValue());
            CloseableHttpResponse response = null;
            try {
                response = client.execute(post.build());
                if (response.getStatusLine().getStatusCode() == 200) {
                    HttpEntity entity = response.getEntity();
                    if (entity != null)
                        responseText = EntityUtils.toString(entity, "UTF-8");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    response.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return responseText;
    }

    public static String getHeader(String url, String appkey) throws Exception {
        RequestBuilder post = RequestBuilder.get(url);
        post.setCharset(Charset.forName("UTF-8"));
        post.setHeader("Content-Type", "application/x-www-form-urlencoded");
        post.setHeader("Appkey", appkey);
        String responseText = "";
        CloseableHttpResponse response = null;
        try {
            response = client.execute(post.build());
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                if (entity != null)
                    responseText = EntityUtils.toString(entity, "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return responseText;
    }

    public static String getAuthorization(String url, String appkey, Map<String, String> paramsMap) throws Exception {
        CloseableHttpClient client = HttpClients.createDefault();
        String responseText = "";
        CloseableHttpResponse response = null;
        try {
            String getUrl = url + "?";
            if (paramsMap != null)
                for (Map.Entry<String, String> param : paramsMap.entrySet())
                    getUrl = getUrl + (String) param.getKey() + "=" + URLEncoder.encode(param.getValue(), "UTF-8");
            HttpGet method = new HttpGet(getUrl);
            method.setHeader("Authorization", appkey);
            log.info("" + getUrl);
            log.info(" " + method.getHeaders("Authorization"));
            response = client.execute((HttpUriRequest) method);
            log.info("" + JSONObject.toJSONString(response));
            HttpEntity entity = response.getEntity();
            if (entity != null)
                responseText = EntityUtils.toString(entity);
        } catch (Exception e) {
            e.getStackTrace();
        } finally {
            try {
                response.close();
            } catch (Exception e) {
                e.getStackTrace();
            }
        }
        return responseText;
    }

    public static String postChangZhouHeader(String url, TreeMap<String, String> paramsMap, String appkey, Long timestamp, String random, String sign, String accessToken) throws Exception {
        RequestBuilder post = RequestBuilder.post(url);
        post.setCharset(Charset.forName("UTF-8"));
        post.setHeader("Content-Type", "multipart/form-data");
        post.setHeader("appid", appkey);
        post.setHeader("timestamp", timestamp + "");
        post.setHeader("nonce", random);
        post.setHeader("signType", "md5");
        post.setHeader("sign", sign);
        if (StringUtils.isNotBlank(accessToken))
            post.setHeader("accessToken", accessToken);
        String responseText = "";
        if (paramsMap != null) {
            for (Map.Entry<String, String> param : paramsMap.entrySet())
                post.addParameter(param.getKey(), param.getValue());
            CloseableHttpResponse response = null;
            try {
                response = client.execute(post.build());
                if (response.getStatusLine().getStatusCode() == 200) {
                    HttpEntity entity = response.getEntity();
                    if (entity != null)
                        responseText = EntityUtils.toString(entity, "UTF-8");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    response.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return responseText;
    }

}
